package com.nomi.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nomi.blog.entity.Follower;
import com.nomi.blog.mapper.FollowerMapper;
import com.nomi.blog.mapper.FollowingMapper;
import com.nomi.blog.service.FollowerService;
import com.nomi.blog.service.FollowingService;
import com.nomi.blog.service.UserInfoService;
import com.nomi.blog.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FollowerServiceImpl implements FollowerService {
    @Autowired
    private FollowerMapper followerMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private FollowingService followingService;

    /**
     * 获取粉丝列表
     * @param userId
     * @return
     */
    @Override
    public Result getFollowerList(Long userId) {
        QueryWrapper<Follower> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Follower> followerList = followerMapper.selectList(queryWrapper);
        return Result.success("粉丝列表获取成功", followerList);
    }

    /**
     * 关注
     * @param userId
     * @param followerUserId
     * @return
     */
    @Override
    @Transactional
    public Result follow(Long userId, Long followerUserId) {
        Follower follower = new Follower();
        follower.setUserId(userId);
        follower.setFollowerUserId(followerUserId);
        int result = followerMapper.insert(follower);
        if (result > 0) {
            // 更新用户关注数
            userInfoService.updateUserFollowingCount(followerUserId, 1);
            // 更新作者粉丝数
            userInfoService.updateUserFollowerCount(userId, 1);
            return Result.success("关注成功");
        } else {
            return Result.fail("关注失败");
        }
    }

    /**
     * 取消关注
     * @param userId
     * @param followerUserId
     * @return
     */
    @Override
    @Transactional
    public Result unfollow(Long userId, Long followerUserId) {
        QueryWrapper<Follower> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("follower_user_id", followerUserId);
        int result = followerMapper.delete(queryWrapper);
        if (result > 0) {
            // 更新用户关注数
            userInfoService.updateUserFollowingCount(followerUserId, -1);
            // 更新作者粉丝数
            userInfoService.updateUserFollowerCount(userId, -1);
            return Result.success("取消关注成功");
        } else {
            return Result.fail("取消关注失败");
        }
    }

    /**
     * 更新用户粉丝数
     * @param userId
     * @param increment
     * @return
     */
    @Override
    @Transactional
    public Result updateFollowerCount(Long userId, int increment) {
        return userInfoService.updateUserFollowerCount(userId, increment);
    }
}
